import React, { Component } from 'react';
import { View, Text, ScrollView } from 'react-native'

class AutoScrollView extends Component {
  static defaultProps = {
    data: [],
    delayTime: 2000,   //默认两秒
    backgroundColor: '#eee',  //默认颜色
    height: 160,  //滚动视图的默认高度
    scrollHeight: 50,  //每次滚动的高度
    borderRadius: 10,  //滚动视图的默认圆角
    startLength: 3,  //默认长度>3时开始滚动
  };

  constructor(props) {
    super(props);
    this.state = {
      runIndex: 0,
      data: this.props.data,
    }
  }
  async componentWillReceiveProps(nextProps, nextContext) {
    // console.log('重新接收数据')
    await this.setState({
      data: nextProps.data
    })

    this.runScroll()
  }

  componentDidMount() {
    this.runScroll()
  }


  /**滚动**/
  runScroll() {
    let runIndex = this.state.runIndex  //开始滚动的下标
    let list = this.state.data    // 数据
    let { delayTime, scrollHeight, startLength } = this.props

    let that = this
    this.timer2 && clearInterval(this.timer2)
    this.timer2 = setInterval(function () {
      // LOG("====>>>>> timer2")
      if (runIndex < list.length - (startLength + 1)) {
        runIndex++
        let scroll_y = runIndex * scrollHeight
        that.scrollview.scrollTo({ x: 0, y: scroll_y, animated: true, })
      } else {
        runIndex = 0
        that.scrollview.scrollTo({ x: 0, y: 0, animated: false, })
      }
      that.setState({
        runIndex: runIndex
      })

    }, delayTime)
  }

  componentWillUnmount() {
    this.timer2 && clearInterval(this.timer2)
  }


  render() {
    let { backgroundColor, height, borderRadius } = this.props
    return (
      <ScrollView showsVerticalScrollIndicator={false}
        ref={(ref) => this.scrollview = ref} style={{
          height: height,
          borderRadius: borderRadius,
        }}>
        {
          this.props.children ?
            this.props.children
            :
            this.state.data.map((item, id) => {
              return (
                <View key={id} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', height: 50, borderBottomWidth: 1, borderColor: '#F0F0FD' }}>
                  <Text>{id}</Text>
                </View>
              )
            })
        }
      </ScrollView>
    );
  }
}

export default AutoScrollView;


